<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./02菜单递归.js"></script>
</head>

<body>
    <script>
        /**
 * 已知如下数组菜单，要求输出树形菜单结构,递归代码实现?
    [
        { id: 1, parent: null, name: '菜单1' },
        { id: 2, parent: 1, name: '菜单1-1' },
        { id: 3, parent: 1, name: '菜单1-2' },
        { id: 4, parent: null, name: '菜单2' },
        { id: 5, parent: 4, name: '菜单2-1' },
    ]

  树形菜单
  [
    {
        id: 1,
        parent: null,
        name: '菜单1',
        children: [
            { id: 2, parent: 1, name: '菜单1-1' },
            { id: 3, parent: 1, name: '菜单1-2' },
        ]
    },
    {
        id: 4,
        parent: null,
        name: '菜单2',
        children: [
            { id: 5, parent: 4, name: '菜单2-1' }
        ]
    }
]
 */
        const list = [
            { id: 1, parent: null, name: '菜单1' },
            { id: 2, parent: 1, name: '菜单1-1' },
            { id: 3, parent: 1, name: '菜单1-2' },
            { id: 4, parent: null, name: '菜单2' },
            { id: 5, parent: 4, name: '菜单2-1' },
            { id: 6, parent: 2, name: '菜单1-1-1' },
        ]

        /**
           menuList = [
                { id: 1, parent: null, name: '菜单1', 
                  children:[
                     { id: 2, parent: 1, name: '菜单1-1' },
                     { id: 3, parent: 1, name: '菜单1-2' },
                ] },
                { id: 4, parent: null, name: '菜单2',chilrend:[] },
           ]
         */

        /**
         * 思路:
         *    遍历数组，找一级节点添加到树型数组
         *    遍历树型数组,递归添加children
         * 
         * @param {*} rootList  一维数组 
         * @param {*} id  父id
         * @param {*} list 返回的树型数组
         */
        const getTreeMenu = (rootList, id, menuList) => {
            // 实现方法体
            for (let item of rootList) {
                if (item.parent === id) {
                    menuList.push(item)
                }
            }
            // 添加子菜单节点
            for (let item of menuList) {
                item.children = []
                getTreeMenu(rootList, item.id, item.children)
            }

            return menuList
        }
        const getlist = (rootlist, id) => {
            let newlist = [];
            rootlist.forEach((item) => {
                if (item.parent === id) {
                    item.children = getlist(rootlist, item.id);
                    if (!item.children[0]) {
                        delete item.children;
                    }
                    newlist.push(item);
                    // console.log(item)
                }
            });
            return newlist;
        };

        /**
         * 
         */
        // let menuList = getTreeMenu(list, null, [])
        let menuList = getlist(list, null)
        console.log(menuList)
    </script>
</body>

</html>